package com.atguigu.springcloud.myloadbalancer;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component("myloadbalancer2")
public class MyLoadBalancerImpl2 implements MyLoadBalancer{

    private AtomicInteger atomicInteger = new AtomicInteger();

    private int getAndIncrement(){
        int current;
        int next;
        do{
            current = atomicInteger.get();
            next = current > Integer.MAX_VALUE ? 0:current+1;
        }while (!atomicInteger.compareAndSet(current,next));
        System.out.println("第几次循环了呀=="+next);
        return next;

    }

    @Override
    public ServiceInstance getInstance(List<ServiceInstance> list) {
        int choosed = getAndIncrement() % list.size();
        return list.get(choosed);
    }
}
